package com.lagou.rabbitmq.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lagou.rabbitmq.constants.OrderConstants;
import com.lagou.rabbitmq.domain.Goods;
import com.lagou.rabbitmq.domain.Order;
import com.lagou.rabbitmq.exception.BaseException;
import com.lagou.rabbitmq.mapper.OrderMapper;
import com.lagou.rabbitmq.service.GoodsService;
import com.lagou.rabbitmq.service.OrderService;
import com.lagou.rabbitmq.vo.OrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @className: OrderServiceImpl
 * @auther: Jerry
 * @date: 2021/3/17 22:08
 * @desctiption: TODO
 * @version: 1.0
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private GoodsService goodsService;

    @Override
    public Order createOrder(OrderVo orderVo) {
        Goods goods = goodsService.getById(orderVo.getGoodsId());
        if (goods == null) {
            throw new BaseException("商品不存在");
        }
        if (goods.getStock() <= 0) {
            throw new BaseException("商品库存不足");
        }

        Order order = new Order();
        order.setQuantity(orderVo.getQuantity());
        order.setOrderState(OrderConstants.TOPAID.getCode());
        order.setUserId(orderVo.getUserId());
        order.setGoodsId(orderVo.getGoodsId());
        order.setTotalFee(orderVo.getPrice());
        order.setGmtCreate(new Date());
        order.setGmtModified(new Date());
        int rows = this.baseMapper.insert(order);
        if (rows == 0) {
            throw new BaseException("订单创建失败");
        }

        return order;
    }

}
